import math

"""
自定义分页类
"""


def iPagination(params):
    ret = {
        "is_prev": True,
        "is_next": True,
        "from": 0,
        "end": 0,
        "current": 0,
        "total_pages": 0,
        "page_size": 0,
        "count": 0,
        # "url": params['url']
    }

    count = int(params['count'])
    page_size = int(params['page_size'])
    page = int(params['page'])
    display = int(params['display'])
    total_pages = int(math.ceil(count / page_size))
    total_pages = total_pages if total_pages > 0 else 1
    if page <= 1:
        ret['is_prev'] = False

    if page >= total_pages:
        ret['is_next'] = False

    semi = int(math.ceil(display / 2))

    if page - semi > 0:
        ret['from'] = page - semi
    else:
        ret['from'] = 1

    if page + semi <= total_pages:
        ret['end'] = page + semi
    else:
        ret['end'] = total_pages

    ret['current'] = page
    ret['total_pages'] = total_pages
    ret['page_size'] = page_size
    ret['count'] = count
    # ret['range'] = range(ret['from'], ret['end'] + 1)
    return ret


def Page(page, page_size, models):
    page = int(page)
    page_size = int(page_size)
    start = (page - 1) * page_size
    stop = start + page_size

    count = models.count()

    data = models.all().reverse()[start:stop]

    # 分页
    page_params = {
        'count': count,
        'page_size': page_size,
        'page': page,
        'display': 3,
    }
    pages = iPagination(page_params)

    return data, pages

# if __name__ == '__main__':
#     page_params = {
#         'total': 100,
#         'page_size': 18,
#         'page': 5,
#         'display': 5,
#         'url': 'http://localhost/report/&p=5',
#         'total_data': 9
#     }
#     pages = iPagination(page_params)
#     print(pages)
